<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | session 操作
// +----------------------------------------------------------------------
namespace Inphp\Core\Services\Http;

use Inphp\Core\Config;
use Inphp\Core\Context;
use Inphp\Core\Db\Redis;
use Inphp\Core\Service;

class Session
{
    /**
     * 缓存名称
     * @param string $name
     * @return string
     */
    public static function getName(string $name): string
    {
        return "SESSION_{$name}";
    }

    /**
     * 初始化客户端的session数据
     */
    public static function init(): void
    {
        $client = Context::getClient();
        if (Service::isCLI()) {
            //从缓存获取
            $sessionId = $client->getSessionId();
            $sessions = Redis::get(self::getName($sessionId));
            $client->sessions = is_array($sessions) ? $sessions : [];
        } else {
            if (session_status() != PHP_SESSION_ACTIVE) {
                @session_start();
            }
            $client->sessions = $_SESSION;
            $client->id = session_id();
        }
    }

    /**
     * 获取session
     * @param string|null $name
     * @param mixed|null $default
     * @return mixed
     */
    public static function get(?string $name = null, mixed $default = null): mixed
    {
        $client = Context::getClient();
        if (empty($client->sessions)) {
            self::init();
        }
        return !is_null($name) ? ($client->sessions[$name] ?? $default): $client->sessions;
    }

    /**
     * 保存session
     * @param string $name
     * @param mixed|null $value
     */
    public static function set(string $name, mixed $value = null): void
    {
        $client = Context::getClient();
        if (is_null($value)) {
            if (isset($client->sessions[$name])) {
                unset($client->sessions[$name]);
            }
        } else {
            $client->sessions[$name] = $value;
        }
        //同步到缓存
        if (Service::isCLI()) {
            $sessionId = $client->getSessionId();
            //保存
            Redis::set(self::getName($sessionId), empty($client->sessions) ? null : $client->sessions, Config::get("server.sessionLifeTime") ?? 7200);
        } else {
            if (session_status() != PHP_SESSION_ACTIVE) {
                @session_start();
            }
            $_SESSION[$name] = $value;
        }
    }

    /**
     * 移除session
     * @param string $name
     */
    public static function delete(string $name): void
    {
        self::set($name);
    }
}